import { ref } from 'vue'
import { defineStore } from 'pinia'
import { setToken as cookiesSetToken, clearToken as cookiesClearToken } from '@/utils/auth'
import { refresh } from '@/api/auth'
import { getToken } from '@/utils/auth'

export const useTokenStore = defineStore('token', () => {
  const timer = ref<NodeJS.Timeout>()
  const token = ref<Token>(getToken())
  const updateToken = (data: Token) => {
    if (timer.value) {
      clearInterval(timer.value)
    }
    token.value = data
    cookiesSetToken(data)
    timer.value = setInterval(checkExpiration, 1000)
  }
  const clearToken = () => {
    token.value = {} as Token
    cookiesClearToken()
    if (timer.value) {
      clearInterval(timer.value)
    }
  }

  const refreshToken = async () => {
    try {
      const response = await refresh(token.value.refreshToken)
      updateToken(response.data)
      return response.data
    } catch (error) {
      clearToken()
      return {} as Token
    }
  }

  const checkExpiration = async () => {
    if (token.value && token.value.expires && token.value.refreshToken) {
      const now = Date.now()
      // 当expires小于当前时间-10秒时触发刷新
      if (token.value.expires <= now - 10000) {
        await refreshToken()
      }
    }
  }
  if (token.value.accessToken) {
    if (timer.value) {
      clearInterval(timer.value)
    }
    timer.value = setInterval(checkExpiration, 1000)
  }

  return { token, updateToken, clearToken }
})
